package com;

import java.io.*;

public class ReaderWriterTest {
    static String path="d:/temp/io/";
    public  static void main(String[] args) throws IOException {
        ReaderWriterTest rwt=new ReaderWriterTest();
        rwt.readFile();
        rwt.writeFile();
        rwt.replaceFile();
    }

    public void replaceFile() throws IOException{
        Reader fr=new FileReader("d:/temp/io/"+ File.separator+"1.txt");

        int l=-1;
        char[] buf=new char[1024];
        BufferedReader br=new BufferedReader(fr);


        StringBuffer sb=new StringBuffer();

        while ((l= br.read(buf)) > -1){
            sb.append(buf,0,buf.length);
        }
        //替换字符串中指定的内容
        String res= sb.toString().replace("{name}","ww")
                .replace("{type}","dog")
                .replace("{master}","zs");
        //回写文件
        Writer fw=new FileWriter("d:/temp/io/"+File.separator+"pet.txt");
        BufferedWriter bw=new BufferedWriter(fw);

        bw.write(res);
        bw.flush(); //立刻把缓冲数据刷到磁盘
        bw.close();
        fw.close();
    }

    /**
     * 复制字符文件
     * @throws IOException
     */

    public void copyFile() throws IOException{
        Reader fr=new FileReader(path+ File.separator+"1.txt");
        Writer fw=new FileWriter("d:/temp/io/"+File.separator+"write.txt");
        int l=-1;
        char[] buf=new char[1024];
        BufferedReader br=new BufferedReader(fr);
        BufferedWriter bw=new BufferedWriter(fw);

        while ((l= br.read(buf)) > -1){
            bw.write(buf,0,buf.length);
        }
        bw.flush(); //立刻把缓冲数据刷到磁盘
        bw.close();
        fw.close();
    }

    public void writeFile() throws IOException{
        Writer fr=new FileWriter("d:/temp/io/"+File.separator+"write.txt");
        BufferedWriter bw=new BufferedWriter(fr);
        bw.write("我热爱中国#");
        bw.flush();
        bw.close();

    }

    private void readFile() throws IOException {
        Reader fr=new FileReader(path+ File.separator+"1.txt");
        int l=-1;
        char[] buf=new char[1024];
        BufferedReader br=new BufferedReader(fr);
        StringBuffer sb=new StringBuffer();
        while ((l= br.read(buf)) > -1){
            sb.append(buf,0,buf.length);
        }
        fr.close();
        System.out.println(sb.toString());

    }
}
